package com.fccommunity.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.fccommunity.R;
import com.fccommunity.base.BaseActivity;
import com.fccommunity.widget.ProgressWebView;


/**
 * Created by yiwei on 16/4/8.
 */
public class WebViewActivity extends BaseActivity {

    private String title;
    private String url = "www.baidu.com";
    private ProgressWebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        setContentView(R.layout.activity_webview);
        webview = (ProgressWebView) findViewById(R.id.webview);
        initWebView();

        webview.loadUrl(url);
    }

    @Override
    protected void initTitle() {
        titleBar.setTitle(title);
        titleBar.setLeftImageResource(R.mipmap.back);
        titleBar.setLeftClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWebView() {
        WebSettings webSettings = webview.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);

        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }

        });
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if(intent != null){
            title = intent.getStringExtra("title");
            url = intent.getStringExtra("url");
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if( webview.canGoBack()){
                webview.goBack();
                return true;
            }else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public static Intent newIntent(Context context, String title, String url){
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        return intent;
    }

}
